from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session

engine = create_engine("mysql+pymysql://root:123456@127.0.0.1/uniapp_shop", echo=True)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

db: Session = SessionLocal()


def query_result(sql: str):
    """
    序列化数据库查询结果
    :param sql: sql查询语句
    :return: list数据结果
    """
    try:
        sql_result = db.execute(sql)
        return [dict(zip(result.keys(), result)) for result in sql_result]
    except Exception as e:
        print(e)
        return []


def insert_data(sql: str):
    """
    执行修改。插入。删除sql
    :param sql: sql语句
    :return: 结果字符串
    """
    try:
        sql_result = db.execute(sql)
        db.commit(sql_result)
        return '操作成功!'
    except Exception as e:
        print(e)
        db.rollback()
        return '操作失败!'


# if __name__ == '__main__':
#     import json
#     json.loads({
# 			"text": "首页",
# 			"pagePath": "pages/index/index",
# 			"iconPath": "static/icon/home.png",
# 			"selectedIconPath": "static/icon/home-active.png"，
# 		})